//
//  ServiceViewController.m
//  CarLifes
//
//  Created by yu on 2017/6/16.
//  Copyright © 2017年 jpas. All rights reserved.
//

#import "ServiceViewController.h"
#import "BannerView.h"
#import "ServiceHandleCell.h"
#import "NewsCell.h"
#import "Utility.h"
#import "VehicleInfoQueryViewController.h"
#import "NearSearchViewController.h"
#import "DiDiDriverViewController.h"

#import "SearchListViewController.h"
#import "SelectListViewController.h"
#import "SearchAnnotation.h"
#import <AMapNaviKit/AMapNaviKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import "NewsDetailViewController.h"
#import "NewsMoreViewController.h"
#import "LocationManager.h"
//#import <AipOcrSdk/AipOcrSdk.h>
#import "HighVioViewController.h"
#import "CTabBarController.h"
#import "LoginViewController.h"
#import "DeviceVersion.h"

@interface ServiceViewController ()<AMapSearchDelegate,UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate>

{
    NSString *_record;
}

//@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) AMapSearchAPI *search;

@property (nonatomic, strong) NSMutableArray *poiAnnotations;

@property (nonatomic, strong) NSArray *newsList;
@property (nonatomic, strong) dispatch_source_t timer;

@end

@implementation ServiceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 获取队并发队列，定时器的回调函数将会在子线程中执行
    // dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    /////=====>>>
    /*
    // 获取主队列，定时器的回调函数将会在子线程中执行
    dispatch_queue_t queue = dispatch_get_main_queue();
    
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    // 该时间表示从现在开始推迟两秒
    dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC);
    
    // 设置定时器的开始时间，间隔时间
    dispatch_source_set_timer(self.timer, start, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(self.timer, ^{
        NSLog(@"------%@", [NSThread currentThread]);
    });
    dispatch_resume(self.timer);
    */
    /* 参数说明:
     // 设置定时器的一些属性
     dispatch_source_set_timer(dispatch_source_t source, // 定时器对象
     dispatch_time_t start, // 定时器开始执行的时间
     uint64_t interval, // 定时器的间隔时间
     uint64_t leeway // 定时器的精度
     );
     */
    NSString *phoneModel = [DeviceVersion deviceVersion];
    PPLog(@"手机型号：%@",phoneModel);
    
    [self initSearch];
    
    [self setupHeaderView];
    
//    [self loadNewsData];
    
    [self.tableView registerNib:NIB_NAMED(@"ServiceHandleCell") forCellReuseIdentifier:NSStringFromClass([ServiceHandleCell class])];
    [self.tableView registerNib:NIB_NAMED(@"NewsCell") forCellReuseIdentifier:NSStringFromClass([NewsCell class])];

    ///////////车牌号识别///////////
//    UIButton *plateBtn = [[UIButton alloc] initWithFrame:CGRectMake(100, 300, 150, 50)];
//    [plateBtn setBackgroundColor:UIColor.brownColor];
//    [plateBtn setTitle:@"车牌号识别" forState:UIControlStateNormal];
//    [self.view addSubview:plateBtn];
//
//    [plateBtn addTarget:self action:@selector(plateLicenseOCR) forControlEvents:UIControlEventTouchUpInside];
}

- (void)setTableView:(UITableView *)tableView {
    _tableView = tableView;
    if (@available(iOS 13.0, *)) {
        UIColor *bgColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
            if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleLight) {
                return kBackGroundLightGrayColor;
            } else {
                return UIColor.systemBackgroundColor;
            }
        }];
        _tableView.backgroundColor = bgColor;
    } else {
        _tableView.backgroundColor = kBackGroundLightGrayColor;
    }
}

//- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection
//{
//    if (@available(iOS 13.0, *)) {
//        if (previousTraitCollection.userInterfaceStyle == UIUserInterfaceStyleLight) {
//            self.tableView.backgroundColor = UIColor.systemBackgroundColor;
//        } else {
//            self.tableView.backgroundColor = kBackgroundColor;
//        }
//    } else {
//        self.tableView.backgroundColor = kBackgroundColor;
//    }
//}

//- (void)plateLicenseOCR {
//    UIViewController *vc = [AipGeneralVC ViewControllerWithHandler:^(UIImage *image) {
//        [self showLoading];
//        [[AipOcrService shardService] detectPlateNumberFromImage:image withOptions:nil successHandler:^(id result) {
//            if(result[@"words_result"]){
//                if([result[@"words_result"] isKindOfClass:[NSDictionary class]]){
//                    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
//                        [self hideLoading];
//                    }];
//                }
//            }
//
//            PPLog(@"detect result = %@",[self jsonToString:result]);
//        } failHandler:^(NSError *err) {
//            PPLog(@"error = %@",err.description);
//            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
//                [self hideLoading];
//                [[[UIAlertView alloc] initWithTitle:@"无法识别该车牌号码" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil] show];
//            }];
//        }];
//    }];
//
//    [self presentViewController:vc animated:YES completion:nil];
//}

#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url];
        }
    }
}

- (NSString *)jsonToString:(id)data {
    if(data == nil) { return nil; }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:NSJSONWritingPrettyPrinted error:nil];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

- (void)setupHeaderView {
    UIView *header = [UIView new];
    // 由于tableviewHeaderView的特殊性，在使他高度自适应之前你最好先给它设置一个宽度
    header.width = [UIScreen mainScreen].bounds.size.width;
    
    NSArray *picImageNamesArray = @[ @"banner_01.jpg",
                                     @"banner_02.jpg",
                                     @"banner_03.jpg",
                                     @"banner_04.jpg",
                                     ];
    SDCycleScrollView *scrollView = [SDCycleScrollView new];
    scrollView.localizationImageNamesGroup = picImageNamesArray;
    [header addSubview:scrollView];
    scrollView.delegate = self;
    
    scrollView.sd_layout
    .leftSpaceToView(header, 0)
    .topSpaceToView(header, 0)
    .rightSpaceToView(header, 0)
    .heightIs(kAutoHeight(170));
    
    [header setupAutoHeightWithBottomView:scrollView bottomMargin:0];
    [header layoutSubviews];
    
    self.tableView.tableHeaderView = header;
}

- (void)loadNewsData {
    [self.requestTool loadNews:@"top" show:YES success:^(NSMutableArray *newsList) {
        if (newsList != nil) {
            NSArray *subarray = [newsList subarrayWithRange:NSMakeRange(0, 10)];
            self.newsList = subarray;
            [self.tableView reloadData];
        }
    } failure:^(NSString *error) {
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return /*section ? self.newsList.count:*/1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (!indexPath.section) {
        ServiceHandleCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ServiceHandleCell class])];
        
        [cell setHandleActionBlock:^(NSInteger index) {
            switch (index) {
                case 1: // 违章查询
                {
                    VehicleInfoQueryViewController *vi = [[VehicleInfoQueryViewController alloc] init];
                    [self.navigationController pushViewController:vi animated:YES];
                }
                    break;
                case 2: // 违章高发地查询
                {
                    [[[UIAlertView alloc] initWithTitle:nil message:@"暂未开通，敬请期待" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil] show];
                    
//                    HighVioViewController *hv = [[HighVioViewController alloc] init];
//                    [self.navigationController pushViewController:hv animated:YES];
                }
                    break;
                case 3: // 附近停车
                {
                    if (![LocationManager isLocationEnabled]) {// 用户拒绝开启定位权限
                        [[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"请在系统设置中开启定位服务(设置>隐私>定位服务>开启)，访问周边搜索" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去设置", nil] show];
                        return;
                    }
                    [self searchPoiWithKeyword:@"停车场"];
                }
                    break;
                case 4: // 周边导航
                {
                    if (![LocationManager isLocationEnabled]) {// 用户拒绝开启定位权限
                        [[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"请在系统设置中开启定位服务(设置>隐私>定位服务>开启)，访问周边搜索" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去设置", nil] show];
                        return;
                    }
                    NearSearchViewController *ns = [[NearSearchViewController alloc] init];
                    ns.locationType = LocationByUserLocation;
                    [self.navigationController pushViewController:ns animated:YES];
                }
                    break;
                case 5: // 加油站
                {
                    if (![LocationManager isLocationEnabled]) {// 用户拒绝开启定位权限
                        [[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"请在系统设置中开启定位服务(设置>隐私>定位服务>开启)，访问周边搜索" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去设置", nil] show];
                        return;
                    }
                    [self searchPoiWithKeyword:@"加油站"];
                }
                    break;
                case 6: // 汽车维修
                {
                    if (![LocationManager isLocationEnabled]) {// 用户拒绝开启定位权限
                        [[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"请在系统设置中开启定位服务(设置>隐私>定位服务>开启)，访问周边搜索" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去设置", nil] show];
                        return;
                    }
                    [self searchPoiWithKeyword:@"汽车维修"];
//                    TestViewController *t = [[TestViewController alloc] init];
//                    [self.navigationController pushViewController:t animated:YES];
                }
                    break;
            }
        }];
        return cell;
    } else {
        return nil;
    }
//    else {
//        NewsCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([NewsCell class])];
//        NewsModel *model = self.newsList[indexPath.row];
//        cell.newsModel = model;
//        return cell;
//    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (!indexPath.section) {
       return [self.tableView cellHeightForIndexPath:indexPath model:nil keyPath:nil cellClass:[ServiceHandleCell class] contentViewWidth:kScreenWidth];
    } else {
        NewsModel *model = self.newsList[indexPath.row];
       return [self.tableView cellHeightForIndexPath:indexPath model:model keyPath:@"newsModel" cellClass:[NewsCell class] contentViewWidth:kScreenWidth];
    }
}

//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    NewsModel *model = self.newsList[indexPath.row];
//    NewsDetailViewController *nd = [[NewsDetailViewController alloc] init];
//    nd.url = model.url;
//    [self.navigationController pushViewController:nd animated:YES];
//}

//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//{
//    if (section) {
//        UIView *headerView = [[UIView alloc] init];
//        headerView.backgroundColor = [UIColor clearColor];
//
//        UIView *bgView = [[UIView alloc] init];
//        bgView.backgroundColor = [UIColor whiteColor];
//        [headerView addSubview:bgView];
//
//        UIView *lineView = [[UIView alloc] init];
//        lineView.backgroundColor = [UIColor orangeColor];
//        [bgView addSubview:lineView];
//
//        UILabel *newsLabel = [[UILabel alloc] init];
//        [bgView addSubview:newsLabel];
//        newsLabel.text = @"资讯推荐";
//        newsLabel.font = Font_NAME_SIZE(@"PingFangSC-Medium", 17);
//
//        UIButton *checkMoreBtn = [[UIButton alloc] init];
//        [bgView addSubview:checkMoreBtn];
//        [checkMoreBtn setTitle:@"更多" forState:UIControlStateNormal];
//        [checkMoreBtn setTitleColor:[UIColor baseCLTextBlackColor] forState:UIControlStateNormal];
//        checkMoreBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
//        checkMoreBtn.titleLabel.font = [UIFont systemFontOfSize:15];
//        [checkMoreBtn addTarget:self action:@selector(moreAction) forControlEvents:UIControlEventTouchUpInside];
//
//        bgView.sd_layout
//        .leftEqualToView(headerView)
//        .rightEqualToView(headerView)
//        .bottomEqualToView(headerView)
//        .heightIs(45);
//
//        lineView.sd_layout
//        .leftSpaceToView(bgView, 12)
//        .centerYEqualToView(bgView)
//        .heightIs(20)
//        .widthIs(4);
//
//        newsLabel.sd_layout
//        .leftSpaceToView(lineView, 10)
//        .centerYEqualToView(lineView)
//        .heightIs(21)
//        .widthIs(90);
//
//        checkMoreBtn.sd_layout
//        .topEqualToView(bgView)
//        .rightSpaceToView(bgView, 15)
//        .bottomEqualToView(bgView)
//        .widthIs(50);
//
//        return headerView;
//    }
//    return nil;
//}

#pragma mark -
- (void)moreAction
{
    NewsMoreViewController *more = [[NewsMoreViewController alloc] init];
    [self.navigationController pushViewController:more animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return /*section ? 55:*/10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 35;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UILabel *versionLabel = [[UILabel alloc] init];
    NSString *appver = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    versionLabel.text = NSStringFormat(@"当前版本：%@",appver);
    versionLabel.font = SYSTEM_FONT(13);
    versionLabel.textColor = kTextGrayColor;
    versionLabel.textAlignment = NSTextAlignmentCenter;
    return versionLabel;
}

/* 根据中心点坐标来搜周边的POI. */
- (void)searchPoiWithKeyword:(NSString *)keyword
{
    _record = keyword;
    
    AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
    request.location = [AMapGeoPoint locationWithLatitude:[self.user.latitude floatValue] longitude:[self.user.longitude floatValue]];
    request.keywords = keyword;
    request.radius   = 2000;
    request.sortrule = 0;
    
    [MBProgressHUD showHUDAddedTo:KEY_WINDOW animated:YES];
    [self.search AMapPOIAroundSearch:request];
}

#pragma mark - Search Delegate

- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
    PPLog(@"SearchError:{%@}", error.localizedDescription);
}

- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    [MBProgressHUD hideHUDForView:KEY_WINDOW];
    //PPLog(@"parking count == %ld",response.pois.count);
    if (response.pois.count == 0)
    {
        [MBProgressHUD showToast:@"未获取到相关内容"];
        return;
    }
    
    [self.mapView removeAnnotations:self.poiAnnotations];
    [self.poiAnnotations removeAllObjects];
    
    [response.pois enumerateObjectsUsingBlock:^(AMapPOI *obj, NSUInteger idx, BOOL *stop) {
        SearchAnnotation *annotation = [[SearchAnnotation alloc] init];
        [annotation setCoordinate:CLLocationCoordinate2DMake(obj.location.latitude, obj.location.longitude)];
        
        [annotation setTitle:obj.name];
        [annotation setSubtitle:obj.address];
        [annotation setName:obj.name];
        [annotation setAddress:obj.address];
        [annotation setDistance:obj.distance];
        [annotation setParkingType:obj.parkingType];
        PPLog(@"name == %@ | distance = %ld | %lf",obj.name,obj.distance,obj.location.latitude);
        [self.poiAnnotations addObject:annotation];
    }];
    
    if (self.poiAnnotations.count == 1) {
        SelectListViewController *select = [[SelectListViewController alloc] init];
        select.selectAnnotation = self.poiAnnotations.firstObject;
        [self.navigationController pushViewController:select animated:YES];
    } else {
        SearchListViewController *list = [[SearchListViewController alloc] init];
        list.naviItemTitle = _record;
        list.annotations = self.poiAnnotations;
        [self.navigationController pushViewController:list animated:YES];
    }
}

- (void)initSearch
{
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
}

- (NSMutableArray *)poiAnnotations {
    if (_poiAnnotations == nil) {
        _poiAnnotations = [NSMutableArray array];
    }
    return _poiAnnotations;
}

- (NSArray *)newsList {
    if (_newsList == nil) {
        _newsList = [NSArray array];
    }
    return _newsList;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
